<template>
  <div>
    <el-drawer :title="title" v-model="visible" :size="500">
      <template #header>
        <div class="flex items-center title">
          <div class="w-[5px] h-[5px] rounded-[50%] bg-[#3721FF] mr-[10px] circle"></div>
          <div class="tits">{{ title }}</div>
        </div>
      </template>
      <div class="w-full h-[1px] bg-[#EFEFEF] line"></div>
      <div class="pt-[30px]">
        <el-form v-model="form" label-width="80" :rules="rules" ref="formRef" :model="form">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="地区" prop="areaId">
                <template #label>
                  <div class="flex text-[#101010] items-center"> 地区 </div>
                </template>
                <el-select
                  v-model="form.areaId"
                  placeholder="请选择地区"
                  filterable
                  @change="handleChangeArea"
                >
                  <el-option
                    :label="item.stateName"
                    :value="item.id"
                    v-for="(item, index) in areaList"
                    :key="index"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="规则类型" prop="ruleType">
                <template #label>
                  <div class="flex text-[#101010] items-center"> 规则类型 </div>
                </template>
                <el-select v-model="form.ruleType" placeholder="请选择规则类型">
                  <el-option
                    :label="item.name"
                    :value="item.code"
                    v-for="(item, index) in ruleType"
                    :key="index"
                  />
                </el-select>
                <div class="w-full maxnum" v-if="form.ruleType === '1' || form.ruleType === '2'">
                  <div class="w-[11px] h-[30px] relative left-[10px] icon">
                    <img :src="LinkPng" class="w-full h-full object-contain" />
                  </div>
                  <el-input
                    v-model="form.ruleValue"
                    :placeholder="`请输入${form.ruleType == 1 ? '最大购买数' : '最大订单金额'}`"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="hide" style="border-radius: 6px !important; width: 109px"
            >取消
          </el-button>
          <el-button
            type="primary"
            color="#3721FF"
            @click="onSubmit"
            style="border-radius: 6px !important; width: 109px"
            >确定
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { FormInstance } from 'element-plus'
import { GlobeStateApi } from '@/api/setting/area'
import Fields from './fields.vue'
import LinkPng from '@/assets/mall/trade/order/link.png'
import { formError } from '@/utils'
import * as AdviceApi from '@/api/mall/trade/advice'
import { getGlobeState } from '@/api/publicInterf'

const props = defineProps({
  info: {
    type: Object as () => AdviceApi.AdviceItemsVO,
    deault: () => []
  }
})

const emit = defineEmits(['confirm'])

const title = ref('新增')
const form = ref<AdviceApi.AdviceItemsVO>({
  ruleValue: '',
  areaId: undefined,
  id: undefined,
  areaName: undefined,
  ruleType: undefined
})

const formRef = ref<FormInstance | null>(null)

const areaList = ref([])

const ruleType = ref([
  {
    name: '最大购买数',
    code: '1'
  },
  {
    name: '最大订单金额',
    code: '2'
  }
])

const rules = {
  ruleType: [{ required: true, message: '请选择规则类型', trigger: 'change' }],
  areaId: [{ required: true, message: '请选择地区', trigger: 'change' }]
}

type FormType = {
  fieldName: string
  variableName: string
  type: 'system' | 'custom'
}

const list = ref<FormType[]>([])

const fieldsRef = ref<InstanceType<typeof Fields> | null>(null)

const isQueryed = ref(false)

const visible = ref(false)

watch(
  () => props.info,
  (val) => {
    if (val) {
      title.value = '编辑'
      form.value.id = val.id
      form.value.areaId = val.areaId
      form.value.areaName = val.areaName
      form.value.ruleType = val.ruleType
      form.value.ruleValue = val.ruleValue
    }
  }
)

/**地区ID变化时，获取地区名称*/
const handleChangeArea = () => {
  form.value.areaName = areaList.value.find((item) => item.id === form.value.areaId)?.stateName
}

/**
 * 查询
 */
const onSubmit = () => {
  formRef.value?.validate((bool) => {
    if (bool) {
      if (form.value.ruleType == '1') {
        form.value.ruleType = '最大购买数'
      } else if (form.value.ruleType == '2') {
        form.value.ruleType = '最大订单金额'
      }
      emit('confirm', {
        type: 'confirm',
        data: form.value
      })
    } else {
      formError()
    }
  })
}

const handleField = () => {
  fieldsRef.value?.show()
}

const handleCustomField = () => {
  list.value.push({
    fieldName: '',
    variableName: '-',
    type: 'custom'
  })
}

const delRow = (row: FormType) => {
  list.value = list.value.filter((item) => item !== row)
}

const show = () => {
  visible.value = true
}

const hide = () => {
  visible.value = false
}

const initPromise = async () => {
  let res = await Promise.all([getGlobeState({ page: 1, size: 1000 })])
  areaList.value = res[0] || []
}

onMounted(() => {
  initPromise()
})

defineExpose({
  show,
  hide
})
</script>

<style lang="scss" scoped>
:deep(.el-drawer__header) {
  margin-bottom: 0px;
}

:deep(.el-button) {
  height: 39px !important;
  border-radius: 6px !important;
}
</style>
